<!--  -->
<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="10">
        <div class="grid-content bg-purple personal-night">
          <div class="bg-img"></div>
          <div>
            <el-avatar :src="profile" :size="110" class="img-left"></el-avatar>
          </div>
          <div>
            <div class="card-user">{{ formLabelAlign.UserName }}</div>
            <div class="information-left">
              <span>胡歌</span>
              <el-divider direction="vertical"></el-divider>
              <span>Web Developer</span>
            </div>
            <div class="information-left">
              <span>手机：</span>
              <span>{{ formLabelAlign.PhoneNumber }}</span>
            </div>
            <el-link :underline="false" href="gitee" class="link-box"
              >lishenhai.gitee.com</el-link
            >
          </div>
          <div class="card-footer">
            <div>
              <div>关注</div>
              <div class="size-footer">23</div>
            </div>
            <div>
              <div>粉丝</div>
              <div class="size-footer">344</div>
            </div>
            <div>
              <div>获赞</div>
              <div class="size-footer">1245</div>
            </div>
          </div>
        </div></el-col
      >
      <el-col :span="14"
        ><div class="grid-content bg-purple personal-night">
          <el-tabs :tab-position="tabPosition" style="height: 535px">
            <el-tab-pane label="我的头像">
              <h4>修改头像</h4>
              <el-upload
                action="#"
                :auto-upload="true"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="btn-box">
                <el-button type="success" @click="DetermineProfile"
                  >确定</el-button
                >
                <el-button type="info" @click="CleanUpProfile">清除</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="密码设置">
              <h4>修改密码</h4>
              <el-form
                :model="ruleForm"
                status-icon
                :rules="rules"
                ref="ruleForm"
                label-width="70px"
                class="password-box"
              >
                <el-form-item label="旧密码" prop="oldPass">
                  <el-input
                    type="password"
                    v-model="ruleForm.oldPass"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="pass">
                  <el-input
                    type="password"
                    v-model="ruleForm.pass"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                  <el-input
                    type="password"
                    v-model="ruleForm.checkPass"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('ruleForm')"
                    >提交</el-button
                  >
                  <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="个人信息">
              <h4>修改个人信息</h4>
              <el-form
                label-width="80px"
                :model="informationForm"
                class="password-box"
              >
                <el-form-item label="用户名">
                  <el-input v-model="informationForm.UserName"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="informationForm.gitee"></el-input>
                </el-form-item>
                <el-form-item label="手机">
                  <el-input v-model="informationForm.PhoneNumber"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="ModifyInformation('ruleForm')"
                    >提交</el-button
                  >
                  <el-button @click="ResetInformation">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="赞赏作者">赞赏作者</el-tab-pane>
          </el-tabs>
        </div></el-col
      >
    </el-row>
  </div>
</template>

<script>
export default {
  name: "PersonalCenter",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      imageUrl: "",
      informationForm: {
        //修改个人信息存储
        UserName: "",
        PhoneNumber: "",
        gitee: "",
      },
      formLabelAlign: {
        UserName: "小胡",
        PhoneNumber: "17675467725",
        gitee: "https://gitee.com/lishenhai/",
      },
      OldPassword: "",
      NewPassword: "",
      ConfirmNewPassword: "",
      profile: require("@/assets/bulbasaur.png"),
      tabPosition: "left",
      data: [],
      ruleForm: {
        pass: "",
        checkPass: "",
        oldPass: "",
      },
      rules: {
        oldPass: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
      },
    };
  },
  created() {},
  mounted() {
    this.CloneInformation();
  },
  methods: {
     // 模拟用户头像上传成功
     handleAvatarSuccess(res, file) {
      // 由于我们没有真实上传，可以不做任何操作，也可用这个钩子确认图片上传成功
      // 在此示例中无需处理，因为直接用FileReader完成预览
    },
    // 修改头像确认按钮
    DetermineProfile() {
      if (this.imageUrl !== "") {
        this.profile = this.imageUrl; //更新当前页面头像
        this.$bus.emit("determineProfile", this.imageUrl); //将头像传给sys-content更新
        // console.log("Emitting event with profile:", this.profile); // 调试输出
        this.$message.success("头像已更新");

        this.imageUrl = ""; //上传成功后清空图片
      } else {
        this.$message.error("请选择头像图片!");
      }
    },
    // 清空选择头像按钮
    CleanUpProfile() {
      this.imageUrl = "";
    },
    // ☆ 用户头像上传前验证和读取图片
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }

      // 在用户选择图片文件后，利用FileReader读取文件内容，将其转成Base64格式（数据URI），然后用这个Base64字符串实现图片预览
      // FileReader 是浏览器提供的 API，用于异步读取文件（比如用户通过文件选择框选中的图片文件）。它可以把文件内容读取成不同格式，比如文本、DataURL（Base64编码的图片）等
      const reader = new FileReader();
      // 定义 onload 事件处理程序（此时不会执行）
      reader.onload = (e) => {
        this.imageUrl = e.target.result; // 当文件读取完成后，将读取到的 Base64 数据赋值给 this.imageUrl
         this.$message.success("图片选择成功，请点击“确定”按钮更新头像");
      };
      // 3. 调用 readAsDataURL 方法开始读取文件（异步操作）,将文件内容被转换为 Base64 编码的字符串
      reader.readAsDataURL(file);
      // 文件读取完成时，触发 load 事件，执行 onload 事件处理程序，将将读取到的 Base64 数据赋值给 this.imageUrl
      return false; // 阻止自动上传
    },                           //备注：1.你可以根据需要把profile中的图片保存到后端、存入本地或用作页面头像。2.如果之后需要上传到远程服务器，可以替换action属性为你的接口地址，开启自动上传即可。
    //拷贝个人信息给修改处
    CloneInformation() {
      this.informationForm = { ...this.formLabelAlign }; //在ES6中引入的扩展运算符,用于对象的浅拷贝。
    },
    // 修改个人信息确认按钮
    ModifyInformation() {
      this.formLabelAlign = { ...this.informationForm }; //将修改好的信息拷贝，再进行渲染
      this.ResetInformation();
      this.$message({
        message: "添加成功",
        type: "success",
      });
    },
    // 修改个人信息重置按钮
    ResetInformation() {
      this.informationForm = {
        UserName: "",
        PhoneNumber: "",
        gitee: "",
      };
    },
  },
};
</script>
<style lang='less' scoped>
.el-row {
  margin: 1rem 0;
  font-size: 14px;
}
.bg-purple {
  background: #ffffff;
  border: 1px solid #e4e7ed;
}
.grid-content {
  border-radius: 5px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
/*密码框样式*/
.password-box {
  display: flex;
  flex-direction: column;
  align-items: center;
}
//个人信息修改样式
.file-box {
  display: flex;
  flex-direction: column;
  margin-left: 30%;
  align-items: flex-start;
}
/*按钮框样式*/
.btn-box {
  margin: 1.5rem 0;
}
/*超链接样式*/
.link-box {
  color: #333;
  margin-top: 10px;
  font-size: 18px;
  color: #55595c;
}
/*左侧卡片-头像样式*/
.img-left {
  margin-top: -4rem;
  border: 5px solid #e4e7ed;
}
.card-user {
  font-size: 22px;
  margin: 10px 0 20px 0;
}
/*左侧卡片-个人信息样式*/
.information-left {
  margin-top: 10px;
  font-size: 18px;
  color: #55595c;
}
/*左侧卡片-底部布局*/
.card-footer {
  display: flex;
  justify-content: space-evenly;
  font-size: 18px;
  margin: 2rem 0;
}
.size-footer {
  font-size: 16px;
  color: #55595c;
}
.bg-img {
  height: 214px;
  border-radius: 5px 5px 0 0;
  background-image: url("https://img.tukuppt.com/bg_grid/00/21/58/FuyAcVDcxC.jpg!/fh/350");
  background-size: contain;
}
// 修改用户头像部分
.el-upload {
  cursor: pointer;
}
// 鼠标移动到上传框-边框变色
.avatar-uploader-icon:hover {
  border-color: #409eff;
}
// 上传框样式设置
.avatar-uploader-icon {
  overflow: hidden;
  border-radius: 6px;
  border: 1px dashed #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
// 选取头像大小设置
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>